using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
#if UNITY_ANDROID || UNITY_IOS
using Gj.TapTap;
//using GoogleMobileAds.Api;
#endif

namespace Gj
{
    // 需要安装GoogleMobileAds和Unity.Ad
    public class AdManager
    {

        [System.Serializable]
        public enum Platform
        {
            GoogleMobile,
            Iron,
            YomobGoogle,
            YomobChina,
            Mi,
            Huawei,
            Uc,
            TapADN,
        }

        [System.Serializable]
        public enum AdType
        {
            Banner,
            Interstitial,
            Reward,
        }

        public interface PlatformAdapt
        {
            Task Init();
            bool IsLoaded();
            Task Show();
            void Bind(Action close, Action fail, Action reward);
            Task Banner(string unit);
            Task Interstitial(string unit);
            Task Reward(string unit);
        }

        [System.Serializable]
        public struct AdUnit
        {
            public string key;
            public AdType type;
            public Platform platform;
            public string ios;
            public string android;
            internal bool isPre;
        }

        [System.Serializable]
        public struct AdPlatformInfo
        {
            public Platform platform;
            public bool isTest;
        }
        public static AdSettings settings;

        public static Dictionary<Platform, string> DefinePlatform = new Dictionary<Platform, string>
        {
            {Platform.GoogleMobile, "google_mobile"},
            {Platform.Iron, "iron"},
            {Platform.YomobChina, "yomob_china"},
            {Platform.YomobGoogle, "yomob_google"},
            {Platform.Mi, "mi"},
            {Platform.Huawei, "huawei"},
            {Platform.Uc, "uc"},
            {Platform.TapADN, "tap"},
        };
        public static Dictionary<Platform, PlatformAdapt> map = new Dictionary<Platform, PlatformAdapt>();
        public static Dictionary<string, List<AdUnit>> unitMap = new Dictionary<string, List<AdUnit>>();
        public static bool IsChina = false;
        public static List<Platform> allow;

        private static Action<bool> currentCallback;
        private static bool isClosed = false;
        private static bool isReward = false;
        private static AdUnit current;
        static AdManager()
        {
            settings = LoadSettings();
        }
        public static void BindAllow(List<Platform> include)
        {
	        allow = include;
        }

        public static IEnumerator Init()
        {

#if UNITY_ANDROID || UNITY_IOS
			foreach (var info in settings.platforms)
			{
				PlatformAdapt adapt;
				switch (info.platform)
				{
					// case Platform.Unity:
					// 	Debug.Log("ad => unity,"+info.isTest);
					// 	adapt = new UnityAd(info.isTest);
					// 	break;
					// case Platform.GoogleMobile:
					// 	Debug.Log("ad => google,"+info.isTest);
					// 	adapt = new GoogleMobileAd(info.isTest);
					// 	break;
					// case Platform.Iron:
					// 	Debug.Log("ad => iron,"+info.isTest);
					// 	adapt = new IronAd(info.isTest);
					// 	break;
					case Platform.YomobChina:
					case Platform.YomobGoogle:
						Debug.Log("ad => yomob,"+info.isTest);
						adapt = new YomobAd(info.isTest);
						break;
					case Platform.Mi:
						Debug.Log("ad => mi,"+info.isTest);
						adapt = new CommonAd(info.platform, settings.miAndroidGameId, info.isTest);
						break;
					// case Platform.TapADN:
					// 	Debug.Log("ad => tap,"+info.isTest);
					// 	adapt = new TapADNAd(info.isTest);
					// 	break;
					default:
						continue;
				}
				yield return adapt.Init();
				adapt.Bind(close, fail, reward);
				map.Add(info.platform, adapt);
			}

			for (var i = 0; i < settings.units.Count; i++)
			{
				var unit = settings.units[i];
				unit.isPre = false;
				List<AdUnit> list;
				if (!unitMap.ContainsKey(unit.key))
				{
					list = new List<AdUnit>();
					unitMap.Add(unit.key, list);
				}
				else
				{
					list = unitMap[unit.key];
				}
				list.Add(unit);
			}
#endif
            yield break;
        }
        static void fail()
        {
            if (isClosed) return;
            isClosed = true;
            
            if (currentCallback != null)
            {
                currentCallback(false);
            }
        }

        static void close()
        {
            if (isClosed) return;
            isClosed = true;
            
            AnalyticsManager.Event(isReward ? "adComplete" : "adSkip", new Dictionary<string, object> { { "plane", current.key }, { "platform", current.platform }, { "type", current.type } });
            if (currentCallback != null)
            {
                currentCallback(isReward);
            }
        }

        static void reward()
        {
            if (isClosed) return;
            isReward = true;
            
            AnalyticsManager.Event("adReward", new Dictionary<string, object> { { "plane", current.key }, { "platform", current.platform }, { "type", current.type } });
        }

        private static AdSettings LoadSettings()
        {
            AdSettings loadedSettings = (AdSettings)Resources.Load("AdSettings", typeof(AdSettings));
            if (loadedSettings == null)
            {
                loadedSettings = ScriptableObject.CreateInstance<AdSettings>();
                Debug.Log("AdSettings is not exist (Resources)");
            }
            return loadedSettings;
        }

        public static IEnumerator ShowAd(string key, AdType adType, Action<bool> callback)
        {
            if (!unitMap.ContainsKey(key))
            {
                Debug.Log("Unit " + key + " is not exist settings");
                yield break;
            }
            var unitList = unitMap[key];
            AdUnit current = new AdUnit();
            foreach (var unit in unitList)
            {
                if (unit.type != adType) continue;
                current = unit;
                // todo 调度策略
            }

            if (current.key == null)
            {
                Debug.Log("Unit " + key + " not find adapt");
                yield break;
            }

            yield return ShowAdInline(current, callback);
        }

        public static Platform GetPlatform(string key)
        {
            Platform p;
            switch (key)
            {
                case "google":
                    p = Platform.GoogleMobile;
                    break;
                case "yomob":
                    if (IsChina)
                    {
                        p = Platform.YomobChina;
                    }
                    else
                    {
                        p = Platform.YomobGoogle;
                    }
                    break;
                case "mi":
                    p = Platform.Mi;
                    break;
                case "huawei":
                    p = Platform.Huawei;
                    break;
                case "uc":
                    p = Platform.Uc;
                    break;
                default:
                    p = Platform.Iron;
                    break;
            }
            if (allow != null && allow.Count > 0)
            {
                if (!allow.Contains(p))
                {
                    return allow[0];
                }
            }

            return p;
        }

        public static IEnumerator PreLoad(string key, Platform p, AdType adType)
        {
#if UNITY_ANDROID || UNITY_IOS
            if (!unitMap.ContainsKey(key))
            {
                Debug.Log("Unit " + key + " is not exist settings");
                yield break;
            }
            var unitList = unitMap[key];
            AdUnit current = new AdUnit();
            foreach (var unit in unitList)
            {
                if (unit.type != adType) continue;
                if (unit.platform != p) continue;
                current = unit;
            }

            if (current.key == null)
            {
                Debug.Log("Unit " + key + " not find adapt");
                yield break;
            }

            if (current.isPre)
            {
                yield break;
            }

            AnalyticsManager.Event("adPreLoad", new Dictionary<string, object> { { "plane", key }, { "platform", p }, { "type", adType } });
            yield return LoadAdInlineAsync(current);
            current.isPre = true;
#else
	        yield break;
#endif
        }

        public static IEnumerator ShowAd(string key, Platform p, AdType adType, Action<bool> callback)
        {
#if UNITY_ANDROID || UNITY_IOS
            if (!unitMap.ContainsKey(key))
            {
                Debug.Log("Unit " + key + " is not exist settings");
                yield break;
            }
            Debug.Log("Unit " + key + " is exist settings");
            var unitList = unitMap[key];
            AdUnit current = new AdUnit();
            foreach (var unit in unitList)
            {
                if (unit.type != adType) continue;
                if (unit.platform != p) continue;
                current = unit;
            }

            if (current.key == null)
            {
                Debug.Log("Unit " + key + " not find adapt");
                yield break;
            }
            Debug.Log("Unit " + key + " find adapt");
            AnalyticsManager.Event("adShow", new Dictionary<string, object> { { "plane", key }, { "platform", p }, { "type", adType } });
            yield return ShowAdInline(current, callback);
#else
	        callback(true);
	        yield break;
#endif
        }

        private static async System.Threading.Tasks.Task LoadAdInlineAsync(AdUnit current)
        {
            var adapt = map[current.platform];
            switch (current.type)
            {
                case AdType.Banner:
#if UNITY_IOS
					await adapt.Banner(current.ios);
#elif UNITY_ANDROID
					await adapt.Banner(current.android);
#endif
                    break;
                case AdType.Interstitial:
#if UNITY_IOS
					await adapt.Interstitial(current.ios);
#elif UNITY_ANDROID
					await adapt.Interstitial(current.android);
#endif
                    break;
                case AdType.Reward:
#if UNITY_IOS
					await adapt.Reward(current.ios);
#elif UNITY_ANDROID
					await adapt.Reward(current.android);
#endif
                    break;
                default:
                    break;
            }
        }
        private static IEnumerator ShowAdInline(AdUnit current, Action<bool> callback)
        {
            var adapt = map[current.platform];
            currentCallback = callback;
            isClosed = false;
            isReward = false;
            AdManager.current = current;
            Debug.Log("show ad inline:"+current.isPre+":"+adapt.IsLoaded());
            if (!current.isPre)
            {
                yield return LoadAdInlineAsync(current);
            }
            while (!adapt.IsLoaded())
            {
	            Debug.Log("show ad inline load:"+adapt.IsLoaded());
                if (isClosed)
                {
                    current.isPre = false;
                    yield break;
                }
                yield return null;
            }
            
            yield return adapt.Show();
        }
    }

#if UNITY_ANDROID || UNITY_IOS
// 	public class UnityAd:AdManager.PlatformAdapt
// 	{
// 		private string unit = null;
// 		private Action close;
// 		private Action reward;
// 		private Action fail;
// InitializationOptions initializationOptions;
//         public BannerAdAnchor bannerAdAnchor = BannerAdAnchor.TopCenter;
//
//         public BannerAdPredefinedSize bannerSize = BannerAdPredefinedSize.Banner;
//         IBannerAd banner;
//         IInterstitialAd interstitial;
//         IRewardedAd rewarded;
//
// 		public UnityAd(bool isTest)
// 		{
// 			var settings = AdManager.settings;
//
//             initializationOptions = new InitializationOptions();
//
// #if UNITY_IOS
//                 if (!string.IsNullOrEmpty(settings.unityIosGameId))
//                 {
//                     initializationOptions.SetGameId(settings.unityIosGameId);
//                 }
// #elif UNITY_ANDROID
//                 if (!string.IsNullOrEmpty(settings.unityAndroidGameId))
//                 {
//                     initializationOptions.SetGameId(settings.unityAndroidGameId);
//                 }
// #endif
// 		}
//
// 		 public async Task Init()
// 		{
//             await UnityServices.InitializeAsync(initializationOptions);
//             Debug.Log("ad unity:"+MediationService.InitializationState);
//             // Impression Event
//             MediationService.Instance.ImpressionEventPublisher.OnImpression += ImpressionEvent;
// 			return;
// 		}
//
// 		public void Clear()
// 		{
// 			this.banner = null;
// 			this.interstitial = null;
// 			this.rewarded = null;
// 		}
//
// 		public bool IsLoaded()
// 		{
// 			if (this.rewarded != null)
// 			{
// 				// Debug.LogError("reward:"+this.rewarded.AdState);
// 				return this.rewarded.AdState == AdState.Loaded;
// 			} 
// 			else if (this.interstitial != null)
// 			{
//                 return this.interstitial.AdState == AdState.Loaded;
// 			}
// 			else if (this.banner != null)
// 			{
//                 // return this.banner.AdState == AdState.Loaded;
// 				return true;
// 			}
// 			else
// 			{
// 				return true;
// 			}
// 		}
//
// 		public async Task Show()
// 		{
//             try
//             {
//                 if (this.rewarded != null)
// 				{
// 					var showOptions = new RewardedAdShowOptions { AutoReload = true };
// 					await this.rewarded.ShowAsync(showOptions);
// 				} 
// 				else if (this.interstitial != null)
// 				{
// 					var showOptions = new InterstitialAdShowOptions { AutoReload = true };
// 					await this.interstitial.ShowAsync(showOptions);
// 				}
// 				else if (this.banner != null)
// 				{
// 					await this.banner.LoadAsync();
// 				}
//             }
//             catch (LoadFailedException e)
//             {
// 				AdFailedLoad(e);
//                 // We will handle the failure in the OnFailedLoad callback
//             }
//             catch (ShowFailedException e)
//             {
//                 AdFailedLoad(e);
//             }
// 		}
//
// 		public void Bind(Action close, Action fail, Action reward)
// 		{
// 			this.close = close;
// 			this.fail = fail;
// 			this.reward = reward;
// 		}
//
// 		public async Task Banner(string unit)
// 		{
// 			Clear();
// 			this.unit = unit;
//             var bannerAdSize = bannerSize.ToBannerAdSize();
// 			banner = MediationService.Instance.CreateBannerAd(unit, bannerAdSize, bannerAdAnchor);
// 			
//             // Load Events
//             banner.OnLoaded += AdLoaded;
//             banner.OnFailedLoad += AdFailedLoad;
// 			// try
// 			// {
// 			// 	await this.banner.LoadAsync();
// 			// }
//             // catch (LoadFailedException e)
//             // {
// 			// 	AdFailedLoad(e);
//             //     // We will handle the failure in the OnFailedLoad callback
//             // }
// 		}
//
// 		public async Task Interstitial(string unit)
// 		{
// 			Clear();
// 			this.unit = unit;
// 			interstitial = MediationService.Instance.CreateInterstitialAd(unit);
//
//             // Load Events
//             interstitial.OnLoaded += AdLoaded;
//             interstitial.OnFailedLoad += AdFailedLoad;
//
//             // Show Events
//             interstitial.OnClosed += AdClosed;
// 			try
// 			{
// 				await this.interstitial.LoadAsync();
// 			}
//             catch (LoadFailedException e)
//             {
// 				AdFailedLoad(e);
//                 // We will handle the failure in the OnFailedLoad callback
//             }
// 		}
//
// 		public async Task Reward(string unit)
// 		{
// 			Clear();
// 			Debug.LogError("reward:"+unit+"->1");
// 			this.unit = unit;
// 			rewarded = MediationService.Instance.CreateRewardedAd(unit);
//
// 			Debug.LogError("reward:"+unit+"->2"+rewarded);
//             // Load Events
//             rewarded.OnLoaded += AdLoaded;
//             rewarded.OnFailedLoad += AdFailedLoad;
//
//             // Show Events
//             rewarded.OnClosed += AdClosed;
//             rewarded.OnUserRewarded += UserRewarded;
//             rewarded.OnClicked += AdClicked;
//             try
//             {
// 	            await this.rewarded.LoadAsync();
//             }
//             catch (LoadFailedException e)
//             {
// 	            AdFailedLoad(e);
// 	            // We will handle the failure in the OnFailedLoad callback
//             }
//             catch (Exception e)
//             {
// 	            Debug.Log(e);
// 	            this.fail();
//             }
//
//             if (this.rewarded.AdState == AdState.Unloaded)
//             {
// 	            this.fail();
//             }
// 		}
//         void AdFailedLoad(LoadFailedException e)
//         {
// 	        Debug.Log(e);
// 			this.fail();
//         }
//         void AdFailedLoad(ShowFailedException e)
//         {
// 	        Debug.Log(e);
// 			this.fail();
//         }
//
//         void AdClosed(object sender, EventArgs args)
//         {
// 			this.close();
//         }
//         void UserRewarded(object sender, RewardEventArgs e)
//         {
// 			this.reward();
//             // Debug.Log($"User Rewarded! Type: {e.Type} Amount: {e.Amount}");
//         }
//         void AdClicked(object sender, EventArgs args)
//         {
// 	        this.reward();
//         }
//
//         void AdLoaded(object sender, EventArgs e)
//         {
//             Debug.Log("Ad loaded");
//         }
//
//         void AdFailedLoad(object sender, LoadErrorEventArgs e)
//         {
//             Debug.Log("Failed to load ad");
//             Debug.Log(e.Message);
// 			this.fail();
//         }
//
//         void ImpressionEvent(object sender, ImpressionEventArgs args)
//         {
//             // var impressionData = args.ImpressionData != null ? JsonUtility.ToJson(args.ImpressionData, true) : "null";
// 			// this.reward();
// 			// this.close();
//             // Debug.Log($"Impression event from ad unit id {args.AdUnitId} : {impressionData}");
//         }
// 	}
// 	public class IronAd:AdManager.PlatformAdapt
// 	{
// 		private string unit = null;
// 		private Action close;
// 		private Action reward;
// 		private Action fail;
//
// 		private bool isTest;
//
//         bool banner;
//         bool interstitial;
//         bool rewarded;
//
// 		public IronAd(bool isTest)
// 		{
// 			var settings = AdManager.settings;
//
// 			IronSourceEvents.onSdkInitializationCompletedEvent += SdkInitializationCompletedEvent;
// 			IronSourceEvents.onRewardedVideoAdOpenedEvent += ()=>RewardedVideoOnAdOpenedEvent(null);
// 			IronSourceRewardedVideoEvents.onAdOpenedEvent += RewardedVideoOnAdOpenedEvent;
// 			IronSourceEvents.onRewardedVideoAdClosedEvent += ()=>RewardedVideoOnAdClosedEvent(null);
// 			IronSourceRewardedVideoEvents.onAdClosedEvent += RewardedVideoOnAdClosedEvent;
// 			IronSourceEvents.onRewardedVideoAdReadyEvent += () => RewardedVideoOnAdAvailable(null);
// 			IronSourceRewardedVideoEvents.onAdAvailableEvent += RewardedVideoOnAdAvailable;
// 			IronSourceEvents.onRewardedVideoAdLoadFailedEvent += (err) => RewardedVideoOnAdUnavailable();
// 			IronSourceRewardedVideoEvents.onAdUnavailableEvent += RewardedVideoOnAdUnavailable;
// 			IronSourceEvents.onRewardedVideoAdShowFailedEvent += (err) => RewardedVideoOnAdShowFailedEvent(err, null);
// 			IronSourceRewardedVideoEvents.onAdShowFailedEvent += RewardedVideoOnAdShowFailedEvent;
// 			IronSourceEvents.onRewardedVideoAdRewardedEvent += (placement)=>RewardedVideoOnAdRewardedEvent(placement, null);
// 			IronSourceRewardedVideoEvents.onAdRewardedEvent += RewardedVideoOnAdRewardedEvent;
// 			IronSourceEvents.onRewardedVideoAdClickedEvent += (placement)=>RewardedVideoOnAdClickedEvent(placement, null);
// 			IronSourceRewardedVideoEvents.onAdClickedEvent += RewardedVideoOnAdClickedEvent;
// 			
// 			//Add AdInfo Interstitial Events
// 			IronSourceEvents.onInterstitialAdReadyEvent += () => InterstitialOnAdReadyEvent(null);
// 			IronSourceInterstitialEvents.onAdReadyEvent += InterstitialOnAdReadyEvent;
// 			IronSourceEvents.onInterstitialAdLoadFailedEvent += (err) => InterstitialOnAdLoadFailed(err);
// 			IronSourceInterstitialEvents.onAdLoadFailedEvent += InterstitialOnAdLoadFailed;
// 			IronSourceEvents.onInterstitialAdOpenedEvent += () => InterstitialOnAdOpenedEvent(null);
// 			IronSourceInterstitialEvents.onAdOpenedEvent += InterstitialOnAdOpenedEvent;
// 			IronSourceEvents.onInterstitialAdClickedEvent += ()=>InterstitialOnAdClickedEvent(null);
// 			IronSourceInterstitialEvents.onAdClickedEvent += InterstitialOnAdClickedEvent;
// 			IronSourceEvents.onInterstitialAdShowSucceededEvent += () => InterstitialOnAdShowSucceededEvent(null);
// 			IronSourceInterstitialEvents.onAdShowSucceededEvent += InterstitialOnAdShowSucceededEvent;
// 			IronSourceEvents.onInterstitialAdShowFailedEvent += (err) => InterstitialOnAdShowFailedEvent(err, null);
// 			IronSourceInterstitialEvents.onAdShowFailedEvent += InterstitialOnAdShowFailedEvent;
// 			IronSourceEvents.onInterstitialAdClosedEvent += () => InterstitialOnAdClosedEvent(null);
// 			IronSourceInterstitialEvents.onAdClosedEvent += InterstitialOnAdClosedEvent;
// 			
// 			//Add AdInfo Banner Events
// 			IronSourceBannerEvents.onAdLoadedEvent += BannerOnAdLoadedEvent;
// 			IronSourceEvents.onBannerAdLoadFailedEvent += (err) => BannerOnAdLoadFailedEvent(err);
// 			IronSourceBannerEvents.onAdLoadFailedEvent += BannerOnAdLoadFailedEvent;
// 			IronSourceEvents.onBannerAdClickedEvent += () => BannerOnAdClickedEvent(null);
// 			IronSourceBannerEvents.onAdClickedEvent += BannerOnAdClickedEvent;
// 			IronSourceEvents.onBannerAdScreenPresentedEvent += () => BannerOnAdScreenPresentedEvent(null);
// 			IronSourceBannerEvents.onAdScreenPresentedEvent += BannerOnAdScreenPresentedEvent;
// 			IronSourceEvents.onBannerAdScreenDismissedEvent += () => BannerOnAdScreenDismissedEvent(null);
// 			IronSourceBannerEvents.onAdScreenDismissedEvent += BannerOnAdScreenDismissedEvent;
// 			IronSourceEvents.onBannerAdLeftApplicationEvent += () => BannerOnAdLeftApplicationEvent(null);
// 			IronSourceBannerEvents.onAdLeftApplicationEvent += BannerOnAdLeftApplicationEvent;
//
// 			if (isTest)
// 			{
// 				this.isTest = isTest;
// 				IronSource.Agent.setMetaData("is_test_suite", "enable");
// 				IronSource.Agent.setAdaptersDebug(true);
// 			}
// 			IronSource.Agent.setManualLoadRewardedVideo(false);
// 			IronSource.Agent.shouldTrackNetworkState(true);
// 		}
// 		private void SdkInitializationCompletedEvent()
// 		{
// 			//Launch test suite
// 			if (isTest)
// 			{
// 				IronSource.Agent.launchTestSuite();
// 			}
// 			Debug.LogError("iron init complete");
// 		}
//
// 		 public async Task Init()
// 		{
// 			
// 			var settings = AdManager.settings;
// #if UNITY_IOS
//                 if (!string.IsNullOrEmpty(settings.ironIosAppKey))
//                 {
// 					IronSource.Agent.init(settings.ironIosAppKey);
//                 }
// #elif UNITY_ANDROID
// 			if (!string.IsNullOrEmpty(settings.ironAndroidAppKey))
// 			{
// 				Debug.Log("iron init:"+settings.ironAndroidAppKey);
// 				IronSource.Agent.init(settings.ironAndroidAppKey);
// 			}
// #endif
// 		}
// 		 /************* RewardedVideo AdInfo Delegates *************/
// // Indicates that there’s an available ad.
// // The adInfo object includes information about the ad that was loaded successfully
// // This replaces the RewardedVideoAvailabilityChangedEvent(true) event
// 		 void RewardedVideoOnAdAvailable(IronSourceAdInfo adInfo) { 
// 			 Debug.Log("RewardedVideoOnAdAvailable");
// 		 }
// // Indicates that no ads are available to be displayed
// // This replaces the RewardedVideoAvailabilityChangedEvent(false) event
// 		 void RewardedVideoOnAdUnavailable() {
// 			 this.close();
// 			 Debug.Log("RewardedVideoOnAdUnavailable");
// 		 }
// // The Rewarded Video ad view has opened. Your activity will loose focus.
// 		 void RewardedVideoOnAdOpenedEvent(IronSourceAdInfo adInfo){
// 			 Debug.Log("RewardedVideoOnAdOpenedEvent");
// 		 }
// // The Rewarded Video ad view is about to be closed. Your activity will regain its focus.
// 		 void RewardedVideoOnAdClosedEvent(IronSourceAdInfo adInfo)
// 		 {
// 			 Debug.Log("RewardedVideoOnAdClosedEvent");
// 			 this.close();
// 		 }
// // The user completed to watch the video, and should be rewarded.
// // The placement parameter will include the reward data.
// // When using server-to-server callbacks, you may ignore this event and wait for the ironSource server callback.
// 		 void RewardedVideoOnAdRewardedEvent(IronSourcePlacement placement, IronSourceAdInfo adInfo){
// 			 Debug.Log("RewardedVideoOnAdRewardedEvent");
// //Placement can return null if the placementName is not valid.
// 			 if(placement != null)
// 			 {
// 				 String rewardName = placement.getRewardName();
// 				 int rewardAmount = placement.getRewardAmount();
// 				 this.reward();
// 			 }
// 		 }
// // The rewarded video ad was failed to show.
// 		 void RewardedVideoOnAdShowFailedEvent(IronSourceError error, IronSourceAdInfo adInfo)
// 		 {
// 			 Debug.Log("RewardedVideoOnAdShowFailedEvent");
// 			 this.fail();
// 		 }
// // Invoked when the video ad was clicked.
// // This callback is not supported by all networks, and we recommend using it only if
// // it’s supported by all networks you included in your build.
// 		 void RewardedVideoOnAdClickedEvent(IronSourcePlacement placement, IronSourceAdInfo adInfo){
// 			 Debug.Log("RewardedVideoOnAdClickedEvent");
// 			 this.reward();
// 		 }
// 		 
// 		 /************* Interstitial AdInfo Delegates *************/
// // Invoked when the interstitial ad was loaded succesfully.
// 		 void InterstitialOnAdReadyEvent(IronSourceAdInfo adInfo) {
// 			 Debug.Log("InterstitialOnAdReadyEvent");
// 		 }
// // Invoked when the initialization process has failed.
// 		 void InterstitialOnAdLoadFailed(IronSourceError ironSourceError)
// 		 {
// 			 Debug.Log("InterstitialOnAdLoadFailed");
// 			 this.fail();
// 		 }
// // Invoked when the Interstitial Ad Unit has opened. This is the impression indication. 
// 		 void InterstitialOnAdOpenedEvent(IronSourceAdInfo adInfo) {
// 			 Debug.Log("InterstitialOnAdOpenedEvent");
// 		 }
// // Invoked when end user clicked on the interstitial ad
// 		 void InterstitialOnAdClickedEvent(IronSourceAdInfo adInfo)
// 		 {
// 			 Debug.Log("InterstitialOnAdClickedEvent");
// 			 this.reward();
// 		 }
// // Invoked when the ad failed to show.
// 		 void InterstitialOnAdShowFailedEvent(IronSourceError ironSourceError, IronSourceAdInfo adInfo)
// 		 {
// 			 Debug.Log("InterstitialOnAdShowFailedEvent");
// 			 this.fail();
// 		 }
// // Invoked when the interstitial ad closed and the user went back to the application screen.
// 		 void InterstitialOnAdClosedEvent(IronSourceAdInfo adInfo)
// 		 {
// 			 Debug.Log("InterstitialOnAdClosedEvent");
// 			 this.close();
// 		 }
// // Invoked before the interstitial ad was opened, and before the InterstitialOnAdOpenedEvent is reported.
// // This callback is not supported by all networks, and we recommend using it only if  
// // it's supported by all networks you included in your build. 
// 		 void InterstitialOnAdShowSucceededEvent(IronSourceAdInfo adInfo) {
// 			 Debug.Log("InterstitialOnAdShowSucceededEvent");
// 		 }
// 		 
// 		 
// 		 /************* Banner AdInfo Delegates *************/
// //Invoked once the banner has loaded
// 		 void BannerOnAdLoadedEvent(IronSourceAdInfo adInfo) 
// 		 {
// 			 Debug.Log("BannerOnAdLoadedEvent");
// 		 }
// //Invoked when the banner loading process has failed.
// 		 void BannerOnAdLoadFailedEvent(IronSourceError ironSourceError) 
// 		 {
// 			 Debug.Log("BannerOnAdLoadFailedEvent");
// 		 }
// // Invoked when end user clicks on the banner ad
// 		 void BannerOnAdClickedEvent(IronSourceAdInfo adInfo) 
// 		 {
// 			 Debug.Log("BannerOnAdClickedEvent");
// 		 }
// //Notifies the presentation of a full screen content following user click
// 		 void BannerOnAdScreenPresentedEvent(IronSourceAdInfo adInfo) 
// 		 {
// 			 Debug.Log("BannerOnAdScreenPresentedEvent");
// 		 }
// //Notifies the presented screen has been dismissed
// 		 void BannerOnAdScreenDismissedEvent(IronSourceAdInfo adInfo) 
// 		 {
// 			 Debug.Log("BannerOnAdScreenDismissedEvent");
// 		 }
// //Invoked when the user leaves the app
// 		 void BannerOnAdLeftApplicationEvent(IronSourceAdInfo adInfo) 
// 		 {
// 			 Debug.Log("BannerOnAdLeftApplicationEvent");
// 		 }
//
// 		public void Clear()
// 		{
// 			this.banner = false;
// 			this.interstitial = false;
// 			this.rewarded = false;
// 		}
//
// 		public bool IsLoaded()
// 		{
// 			if (this.rewarded)
// 			{
// 				Debug.Log("reward:"+IronSource.Agent.isRewardedVideoPlacementCapped(this.unit));
// 				return IronSource.Agent.isRewardedVideoAvailable();
// 			} 
// 			else if (this.interstitial)
// 			{
// 				return IronSource.Agent.isInterstitialReady();
// 			}
// 			else if (this.banner)
// 			{
//                 // return this.banner.AdState == AdState.Loaded;
// 				return true;
// 			}
// 			else
// 			{
// 				return true;
// 			}
// 		}
//
// 		public async Task Show()
// 		{
//             try
//             {
//                 if (this.rewarded)
// 				{
// 					IronSource.Agent.showRewardedVideo(unit);
// 				} 
// 				else if (this.interstitial)
// 				{
// 					IronSource.Agent.showInterstitial(unit);
// 				}
// 				else if (this.banner)
// 				{
// 					IronSource.Agent.displayBanner();
// 				}
//             }
//             catch (Exception e)
//             {
// 	            Debug.Log(e);
// 	            this.fail();
// 	            // We will handle the failure in the OnFailedLoad callback
//             }
// 		}
//
// 		public void Bind(Action close, Action fail, Action reward)
// 		{
// 			this.close = close;
// 			this.fail = fail;
// 			this.reward = reward;
// 		}
//
// 		public async Task Banner(string unit)
// 		{
// 			Clear();
// 			this.unit = unit;
// 			this.banner = true;
//             IronSource.Agent.loadBanner(IronSourceBannerSize.BANNER, IronSourceBannerPosition.BOTTOM);
// 		}
//
// 		public async Task Interstitial(string unit)
// 		{
// 			Clear();
// 			this.unit = unit;
// 			this.interstitial = true;
// 			IronSource.Agent.loadInterstitial();
// 		}
//
// 		public async Task Reward(string unit)
// 		{
// 			Clear();
// 			Debug.Log("reward:"+unit+"->1");
// 			this.unit = unit;
// 			this.rewarded = true;
// 			IronSource.Agent.loadRewardedVideo();
// 		}
// 	}
// 	
//     public class GoogleMobileAd:AdManager.PlatformAdapt
//     {
// 	    private bool isTest;
// 		private bool isLoad;
// 	    private GoogleMobileAds.Api.InterstitialAd interstitial;
// 	    private GoogleMobileAds.Api.RewardedAd rewarded;
// 	    private GoogleMobileAds.Api.BannerView bannerView;
// 		private AppOpenAd appOpenAd;
// 	    private Action closeCallback;
// 	    private Action rewardCallback;
// 	    private Action failCallback;
//
// 	    public GoogleMobileAd(bool isTest)
// 	    {
// 		    this.isTest = isTest;
// 		    MobileAds.Initialize(initStatus =>
// 		    {
// 			    Debug.Log("Initialize "+initStatus);
// 		    });
// 			
// 	    }
// 		public async Task Init(){
// 			
// 		}
// 	    
// 		public AdRequest getRequest()
// 		{
// 			var adRequest = new AdRequest();
// 			adRequest.Keywords.Add("unity-admob-sample");
// 			return adRequest;
// 		}
//
// 		public void HandleOnUserEarnedReward(object sender, Reward args)
// 		{
// 			string type = args.Type;
// 			double amount = args.Amount;
// 			MonoBehaviour.print(
// 				"HandleRewardedAdRewarded event received for "
// 				+ amount.ToString() + " " + type);
// 			if(rewardCallback != null){
// 				rewardCallback();
// 			}
// 		}
//
// 		public bool IsLoaded()
// 		{
// 			if (this.rewarded != null)
// 			{
// 				return this.rewarded.CanShowAd();
// 			} 
// 			else if (this.interstitial != null)
// 			{
// 				return this.interstitial.CanShowAd();
// 			}
// 			else
// 			{
// 				return isLoad;
// 			}
// 		}
//
// 		public async Task Show()
// 		{
// 			if (this.rewarded != null)
// 			{
// 				const string rewardMsg =
//         "Rewarded ad rewarded the user. Type: {0}, amount: {1}.";
// 				this.rewarded.Show((re)=>{
// 					Debug.Log(String.Format(rewardMsg, re.Type, re.Amount));
// 					if(rewardCallback != null){
// 				rewardCallback();
// 			}
// 				});
// 			} 
// 			else if (this.interstitial != null)
// 			{
// 				this.interstitial.Show();
// 			}
// 			else if (this.bannerView != null)
// 			{
// 				this.bannerView.Show();
// 			}
// 		}
//
// 		public void Bind(Action close, Action fail, Action reward)
// 		{
// 			this.closeCallback = close;
// 			this.failCallback = fail;
// 			this.rewardCallback = reward;
// 		}
//
// 		public void Clear()
// 		{
// 			isLoad = false;
// 			if (bannerView != null)
// 			{
// 				bannerView.Destroy();
// 				bannerView = null;
// 			}
// 			if (interstitial != null)
// 			{
// 					interstitial.Destroy();
// 					interstitial = null;
// 			}
// 			if (rewarded != null)
// 			{
// 					rewarded.Destroy();
// 					rewarded = null;
// 			}
// 		}
//
// 		public async Task Banner(string unit)
// 		{
// 			Clear();
// 			bannerView = new GoogleMobileAds.Api.BannerView(unit, AdSize.Banner, AdPosition.Bottom);
// 			// Raised when an ad is loaded into the banner view.
// 			bannerView.OnBannerAdLoaded += () =>
// 			{
// 				Debug.Log("Banner view loaded an ad with response : "
// 					+ bannerView.GetResponseInfo());
// 					isLoad = true;
// 			};
// 			// Raised when an ad fails to load into the banner view.
// 			bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
// 			{
// 				Debug.Log("Banner view failed to load an ad with error : "
// 				          + error);
// 					if (bannerView != null)
// 				{
// 					Debug.Log("Destroying banner ad.");
// 					bannerView.Destroy();
// 					bannerView = null;
// 				}
// 				this.failCallback();
// 			};
// 			// Raised when the ad is estimated to have earned money.
// 			bannerView.OnAdPaid += (AdValue adValue) =>
// 			{
// 				Debug.Log(String.Format("Banner view paid {0} {1}.",
// 					adValue.Value,
// 					adValue.CurrencyCode));
// 				this.rewardCallback();
// 			};
// 			// Raised when an impression is recorded for an ad.
// 			bannerView.OnAdImpressionRecorded += () =>
// 			{
// 				Debug.Log("Banner view recorded an impression.");
// 			};
// 			// Raised when a click is recorded for an ad.
// 			bannerView.OnAdClicked += () =>
// 			{
// 				Debug.Log("Banner view was clicked.");
// 				this.rewardCallback();
// 			};
// 			// Raised when an ad opened full screen content.
// 			bannerView.OnAdFullScreenContentOpened += () =>
// 			{
// 				Debug.Log("Banner view full screen content opened.");
// 			};
// 			// Raised when the ad closed full screen content.
// 			bannerView.OnAdFullScreenContentClosed += () =>
// 			{
// 				Debug.Log("Banner view full screen content closed.");
// 			};
// 			var adRequest = getRequest();
// 			bannerView.LoadAd(adRequest);
// 		}
//
// 		public async Task Interstitial(string unit)
// 		{
// 			Clear();
// 			var adRequest = getRequest();
// 			GoogleMobileAds.Api.InterstitialAd.Load(unit, adRequest,
//           (GoogleMobileAds.Api.InterstitialAd ad, LoadAdError error) =>
//           {
//               // if error is not null, the load request failed.
//               if (error != null || ad == null)
//               {
//                   Debug.Log("interstitial ad failed to load an ad " +
//                             "with error : " + error);
// 				this.failCallback();
//                   return;
//               }
//
//               Debug.Log("Interstitial ad loaded with response : "
//                         + ad.GetResponseInfo());
// 			isLoad = true;
//               interstitial = ad;
// 			  // Raised when the ad is estimated to have earned money.
// 			ad.OnAdPaid += (AdValue adValue) =>
// 			{
// 				Debug.Log(String.Format("Interstitial ad paid {0} {1}.",
// 					adValue.Value,
// 					adValue.CurrencyCode));
// 			};
// 			// Raised when an impression is recorded for an ad.
// 			ad.OnAdImpressionRecorded += () =>
// 			{
// 				Debug.Log("Interstitial ad recorded an impression.");
// 			};
// 			// Raised when a click is recorded for an ad.
// 			ad.OnAdClicked += () =>
// 			{
// 				Debug.Log("Interstitial ad was clicked.");
// 			};
// 			// Raised when an ad opened full screen content.
// 			ad.OnAdFullScreenContentOpened += () =>
// 			{
// 				Debug.Log("Interstitial ad full screen content opened.");
// 			};
// 			// Raised when the ad closed full screen content.
// 			ad.OnAdFullScreenContentClosed += () =>
// 			{
// 				Debug.Log("Interstitial ad full screen content closed.");
// 				this.closeCallback();
// 			};
// 			// Raised when the ad failed to open full screen content.
// 			ad.OnAdFullScreenContentFailed += (AdError error) =>
// 			{
// 				Debug.LogError("Interstitial ad failed to open full screen content " +
// 							"with error : " + error);
// 							this.failCallback();
// 			};
//           });
// 		}
//
// 		public async Task Reward(string unit)
// 		{
// 			Clear();
// 			var adRequest = getRequest();
// 			GoogleMobileAds.Api.RewardedAd.Load(unit, adRequest,
//           (GoogleMobileAds.Api.RewardedAd ad, LoadAdError error) =>
//           {
//               // if error is not null, the load request failed.
//               if (error != null || ad == null)
//               {
//                   Debug.Log("Rewarded ad failed to load an ad " +
//                             "with error : " + error);
// 								 this.failCallback();
//                   return;
//               }
//
//               Debug.Log("Rewarded ad loaded with response : "
//                         + ad.GetResponseInfo());
//
//               rewarded = ad;
// 			  // Raised when the ad is estimated to have earned money.z
// 			ad.OnAdPaid += (AdValue adValue) =>
// 			{
// 				Debug.Log(String.Format("Rewarded ad paid {0} {1}.",
// 					adValue.Value,
// 					adValue.CurrencyCode));
// 				this.rewardCallback();
// 			};
// 			// Raised when an impression is recorded for an ad.
// 			ad.OnAdImpressionRecorded += () =>
// 			{
// 				Debug.Log("Rewarded ad recorded an impression.");
// 			};
// 			// Raised when a click is recorded for an ad.
// 			ad.OnAdClicked += () =>
// 			{
// 				Debug.Log("Rewarded ad was clicked.");
// 				this.rewardCallback();
// 			};
// 			// Raised when an ad opened full screen content.
// 			ad.OnAdFullScreenContentOpened += () =>
// 			{
// 				Debug.Log("Rewarded ad full screen content opened.");
// 			};
// 			// Raised when the ad closed full screen content.
// 			ad.OnAdFullScreenContentClosed += () =>
// 			{
// 				Debug.Log("Rewarded ad full screen content closed.");
// 				this.closeCallback();
// 			};
// 			// Raised when the ad failed to open full screen content.
// 			ad.OnAdFullScreenContentFailed += (AdError error) =>
// 			{
// 				Debug.Log("Rewarded ad failed to open full screen content " +
// 				          "with error : " + error);
// 				this.failCallback();
// 			};
//           });
// 		}
//     }

	// public class TapADNAd:AdManager.PlatformAdapt
 //    {
	//     private bool isTest;
	// 	private bool isLoad;
	//     private Action closeCallback;
	//     private Action rewardCallback;
	//     private Action failCallback;
 //
	//     public TapADNAd(bool isTest)
	//     {
	// 	    this.isTest = isTest;
	// 	    MobileAds.Initialize(initStatus =>
	// 	    {
	// 		    Debug.Log("Initialize "+initStatus);
	// 	    });
	// 		
	//     }
	// 	public async Task Init(){
	// 		
	// 	}
	//     
	// 	public AdRequest getRequest()
	// 	{
	// 		var adRequest = new AdRequest();
	// 		adRequest.Keywords.Add("unity-admob-sample");
	// 		return adRequest;
	// 	}
 //
 //
	// 	public bool IsLoaded()
	// 	{
	// 		return true;
	// 	}
 //
	// 	public async Task Show()
	// 	{
	// 	}
 //
	// 	public void Bind(Action close, Action fail, Action reward)
	// 	{
	// 		this.closeCallback = close;
	// 		this.failCallback = fail;
	// 		this.rewardCallback = reward;
	// 	}
 //
	// 	public void Clear()
	// 	{
	// 		isLoad = false;
	// 	}
 //
	// 	public async Task Banner(string unit)
	// 	{
	// 		Clear();
	// 		
	// 	}
 //
	// 	public async Task Interstitial(string unit)
	// 	{
	// 		Clear();
	// 	}
 //
	// 	public async Task Reward(string unit)
	// 	{
	// 		Clear();
	// 	}
 //    }
    public class YomobAd : AdManager.PlatformAdapt
    {
	    private bool isTest;
	    private string unit = null;
	    private Action close;
	    private Action reward;
	    private Action fail;
	    public YomobAd(bool isTest)
	    {
		    this.isTest = isTest;
		    var settings = AdManager.settings;
#if UNITY_IOS
			// TGSDK.Initialize(settings.yomobIosGameId);
#elif UNITY_ANDROID
		    // TGSDK.Initialize (settings.yomobAndroidGameId);
#endif
		    // TGSDK.SetDebugModel(isTest);
		    // TGSDK.PreloadAdSuccessCallback = OnPreloadAdSuccess;
		    // TGSDK.PreloadAdFailedCallback = OnPreloadAdFailed;
		    // TGSDK.AwardVideoLoadedCallback = OnAwardVideoLoadedCallback;
		    // TGSDK.InterstitialVideoLoadedCallback = OnInterstitialVideoLoadedCallback;
		    // TGSDK.InterstitialLoadedCallback = OnInterstitialLoadedCallback;
		    //
		    // TGSDK.AdShowSuccessCallback = OnAdShowSuccess;
		    // TGSDK.AdShowFailedCallback = OnAdShowFailed;
		    // TGSDK.AdCloseCallback = OnAdClose;
		    // TGSDK.AdClickCallback = OnAdClick;
	    }
		public async Task Init(){
			
		}
	    public void OnPreloadAdSuccess(string ret) {
		    Debug.Log("OnPreloadAdSuccess ."+ret);
	    }

	    public void OnPreloadAdFailed(string error) {
		    Debug.Log("OnPreloadAdFailed ."+error);
	    }

	    public void OnAwardVideoLoadedCallback(string ret) {
		    Debug.Log("OnAwardVideoLoadedCallback ."+ret);
	    }

	    public void OnInterstitialVideoLoadedCallback(string ret) {
		    Debug.Log("OnInterstitialVideoLoadedCallback ."+ret);
	    }

	    public void OnInterstitialLoadedCallback(string ret) {
		    Debug.Log("OnInterstitialLoadedCallback ."+ret);
	    }
	    public void OnAdShowSuccess(string scene, string name) {
		    
		    Debug.Log("OnAdShowSuccess ."+scene+":"+name);
	    }

	    public void OnAdShowFailed(string scene, string name, string error)
	    {
		    this.fail();
	    }

	    public void OnAdClose(string scene, string name, bool award) {
		    if (award)
		    {
			    this.reward();
		    }
		    
		    this.close();
	    }

	    public void OnAdClick(string scene, string name)
	    {
		    Debug.Log("OnAdClick ."+scene+":"+name);
	    }

	    public bool IsLoaded()
	    {
		    // return TGSDK.CouldShowAd(unit);
		    return false;
	    }

	    public async Task Show()
	    {
		    // if (isTest)
		    // {
			   //  TGSDK.ShowTestView(unit);
		    // }
		    // else
		    // {
			   //  TGSDK.ShowAd(unit);
		    // }
	    }

	    public void Bind(Action close, Action fail, Action reward)
	    {
		    this.close = close;
		    this.fail = fail;
		    this.reward = reward;
	    }

	    public async Task Banner(string unit)
	    {
		    this.unit = unit;
		    // TGSDK.PreloadAd();
	    }

	    public async Task Interstitial(string unit)
	    {
		    this.unit = unit;
		    // TGSDK.PreloadAd();
	    }

	    public async Task Reward(string unit)
	    {
		    this.unit = unit;
		    // TGSDK.PreloadAd();
	    }
    }
    
    public class CommonAd : AdManager.PlatformAdapt
    {
	    private AdManager.Platform platform;
	    private bool isTest;
	    private string unit = null;
	    private AdManager.AdType adType;
	    private bool isOk;
	    
	    public delegate void RegisterDelegate(AdManager.Platform platform, bool isOk);
	    public void RegisterHandler(AdManager.Platform platform, bool isOk)
	    {
		    Debug.LogFormat("Ad register:{0},{1}",platform,isOk);
		    this.isOk = isOk;

	    }
	    public CommonAd(AdManager.Platform p, string appId, bool isTest)
	    {
		    this.platform = p;
		    this.isTest = isTest;
#if UNITY_ANDROID && !UNITY_EDITOR
		    try
		    {
			    Run(delegate
			    {
				    var androidRegisterListener = new AndroidRegisterListener(RegisterHandler);
				    AdSDK.CallStatic("register", (int) this.platform, appId, androidRegisterListener);
					AdSDK.CallStatic("setDebugMode", isTest);
			    });
		    }
		    catch (AndroidJavaException exp)
		    {
			    Debug.Log(exp.Message);
		    }
#endif
	    }

		public async Task Init(){

		}

	    public bool IsLoaded()
	    {
#if UNITY_ANDROID && !UNITY_EDITOR
		    return AdSDK.CallStatic<bool>("isLoaded", (int) this.platform, (int) this.adType, unit);
#endif
		    return false;
	    }

	    public async Task Show()
	    {
#if UNITY_ANDROID && !UNITY_EDITOR
		    AdSDK.CallStatic("show", (int) this.platform, (int) this.adType, unit);
#endif
	    }

	    public void Bind(System.Action close, System.Action fail, System.Action reward)
	    {
#if UNITY_ANDROID && !UNITY_EDITOR
			try
            {
                Run(delegate
                {
                    var androidCallbackListener = new AndroidCallbackListener(close, fail, reward);
                    AdSDK.CallStatic("bindCallback", androidCallbackListener);
                });
            }
            catch (AndroidJavaException exp)
            {
                Debug.Log(exp.Message);
            }
#endif
	    }

	    public async Task Banner(string unit)
	    {
		    this.unit = unit;
		    this.adType = AdManager.AdType.Banner;
#if UNITY_ANDROID && !UNITY_EDITOR
			try
            {
                Run(delegate
                {
                    AdSDK.CallStatic("preload", (int) this.platform, (int) AdManager.AdType.Banner, unit);
                });
            }
            catch (AndroidJavaException exp)
            {
                Debug.Log(exp.Message);
            }
#endif
	    }

	    public async Task Interstitial(string unit)
	    {
		    this.unit = unit;
		    this.adType = AdManager.AdType.Interstitial;
#if UNITY_ANDROID && !UNITY_EDITOR
			try
            {
                Run(delegate
                {
                    AdSDK.CallStatic("preload", (int) this.platform, (int) AdManager.AdType.Interstitial, unit);
                });
            }
            catch (AndroidJavaException exp)
            {
                Debug.Log(exp.Message);
            }
#endif
	    }

	    public async Task Reward(string unit)
	    {
		    this.unit = unit;
		    this.adType = AdManager.AdType.Reward;
#if UNITY_ANDROID && !UNITY_EDITOR
			try
            {
                Run(delegate
                {
                    AdSDK.CallStatic("preload", (int) this.platform, (int) AdManager.AdType.Reward, unit);
                });
            }
            catch (AndroidJavaException exp)
            {
                Debug.Log(exp.Message);
            }
#endif
	    } 
	    //以下代码是内部实现
	    //请勿修改
#if UNITY_ANDROID && !UNITY_EDITOR

        public delegate void Action();

        static void Run(Action action)
        {
            activity.Call("runOnUiThread", new AndroidJavaRunnable(action));
        }

        class AndroidRegisterListener : AndroidJavaProxy
        {
            public AndroidRegisterListener(RegisterDelegate Delegate):base("com.ueffort.ad.AdRegisterListener")
            {
                this.registerDelegate = Delegate;
            }

            private RegisterDelegate registerDelegate = null;

            public void onRegister(int platform, bool isOk)
            {
                registerDelegate((AdManager.Platform) platform, isOk);
            }
        }

        class AndroidCallbackListener : AndroidJavaProxy
        {
            public AndroidCallbackListener(System.Action close, System.Action fail, System.Action reward):base("com.ueffort.ad.CallbackListener")
            {
			    this.close = close;
			    this.fail = fail;
			    this.reward = reward;
            }

		    private System.Action close;
		    private System.Action reward;
		    private System.Action fail;

            public void OnPreloadAdSuccess(string ret) {
			    Debug.Log("OnPreloadAdSuccess ."+ret);
		    }

		    public void OnPreloadAdFailed(string error) {
			    Debug.Log("OnPreloadAdFailed ."+error);
		    }

		    public void OnAwardVideoLoadedCallback(string ret) {
			    Debug.Log("OnAwardVideoLoadedCallback ."+ret);
		    }
		    public void OnAdShowSuccess(string scene, string name) {
			    
			    Debug.Log("OnAdShowSuccess ."+scene+":"+name);
		    }

		    public void OnAdShowFailed(string scene, string name, string error)
		    {
			    this.fail();
		    }

		    public void OnAdClose(string scene, string name, bool award) {
			    if (award)
			    {
				    this.reward();
			    }
			    
			    this.close();
		    }

		    public void OnAdClick(string scene, string name)
		    {
			    Debug.Log("OnAdClick ."+scene+":"+name);
		    }
        }

        public static AndroidJavaClass AdSDK = new AndroidJavaClass("com.ueffort.ad.AdSDK");


        static AndroidJavaObject activity =
            new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");

#endif
    }
#endif
}